package com.UnionPayCenter.account.service.impl;

import com.UnionPayCenter.account.entity.FundsBill;
import com.UnionPayCenter.account.entity.dto.FundsBillDTO;
import com.UnionPayCenter.entity.vo.UserVo;
import com.UnionPayCenter.mapper.FundsBillMapper;
import com.UnionPayCenter.mapper.UserMapper;
import com.UnionPayCenter.account.service.FundsBillService;
import com.UnionPayCenter.service.IUserService;
import com.UnionPayCenter.service.ServiceTemplate;
import com.UnionPayCenter.util.Asserts;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class FundsBillServiceImpl implements FundsBillService {

    @Autowired
    private FundsBillMapper fundsBillMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ServiceTemplate serviceTemplate;

    @Override
    public void saveFundsBill(FundsBill fundsBill) {
        // TODO check
        Asserts.notNull(fundsBill, "资金流水记录");
        Asserts.notBlank(fundsBill.getSn(), "流水号");
        Asserts.notNull(fundsBill.getBillType(), "流水类型");

        fundsBillMapper.insert(fundsBill);
    }

    @Override
    public void updateFundsBill(FundsBill fundsBill) {
        Asserts.notBlank(fundsBill.getSn(), "流水号");
        fundsBillMapper.updateByPrimaryKey(fundsBill);
    }

    @Override
    public Page<FundsBill> getFundsBillByCondition(FundsBillDTO fundsBillDTO, Integer page, Integer pageSize) {
        Asserts.notNull(fundsBillDTO, "查询条件");
        Page<FundsBill> fundsBillPage = serviceTemplate.pagination(page, pageSize, () -> fundsBillMapper.selectByCondition(fundsBillDTO));
        for (FundsBill resultBill : fundsBillPage) {
            UserVo userVo = userMapper.selectInfo(resultBill.getUserId());
            if (userVo == null) {
                continue;
            }
            resultBill.setMobile(userVo.getMobile());
        }

        return fundsBillPage;
    }

    @Override
    public Page<FundsBill> getMpFundsBillByCondition(FundsBillDTO fundsBillDTO, Integer page, Integer pageSize) {
        Asserts.notNull(fundsBillDTO, "查询条件");
        Page<FundsBill> fundsBillPage = serviceTemplate.pagination(page, pageSize,
                () -> fundsBillMapper.selectMpFundsByCondition(fundsBillDTO));
        for (FundsBill resultBill : fundsBillPage) {
            UserVo userVo = userMapper.selectInfo(resultBill.getUserId());
            if (userVo == null) {
                continue;
            }
            resultBill.setMobile(userVo.getMobile());
        }

        return fundsBillPage;
    }
}
